from sql_ast import normalize_sql, ast_to_features
from .cosine import weighted_cosine_similarity

def sql_similarity(sql1, sql2):
    """计算两个SQL语句的相似度(0-1)"""
    # 标准化SQL
    ast1 = normalize_sql(sql1)
    ast2 = normalize_sql(sql2)
    
    if not ast1 or not ast2:
        print("警告：至少有一个SQL解析失败")
        return 0.0
    
    # 转换为特征
    features1 = ast_to_features(ast1)
    features2 = ast_to_features(ast2)

    # 计算相似度
    similarity = weighted_cosine_similarity(features1, features2)
    
    # 对完全相同的AST给予满分
    if str(ast1) == str(ast2):
        return 1.0
    
    return similarity